package org.opens.netty.audio;

import javax.sound.sampled.*;
import java.util.Arrays;

/**
 * 功能描述
 *
 * @author: zhangyuming
 */
public class AudioUtils {

    public static TargetDataLine getMicrophone() throws LineUnavailableException {
        AudioFormat format = new AudioFormat(16000, 16, 1, true, true);
        DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
        TargetDataLine microphone = (TargetDataLine) AudioSystem.getLine(info);
        microphone.open(format);
        return microphone;
    }

    public static SourceDataLine getSpeaker() throws LineUnavailableException {
        AudioFormat format = new AudioFormat(16000, 16, 1, true, true);
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
        SourceDataLine speaker = (SourceDataLine) AudioSystem.getLine(info);
        speaker.open(format);
        return speaker;
    }

    public static void main(String[] args) throws LineUnavailableException {
        TargetDataLine microphone = getMicrophone();
        microphone.start();
        new Thread(() -> {
            byte[] buffer = new byte[1024];
            while (true) {
                int bytesRead = microphone.read(buffer, 0, buffer.length);
                System.out.println(Arrays.toString(buffer));
            }
        }).start();
    }

}
